package com.rtx.edi.platform.source.controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rtx.api.enums.FieldValidateType;
import com.rtx.api.utils.FieldValidateUtils;
import com.rtx.edi.model.response.EdiResponse;
import com.rtx.edi.platform.source.bean.PlExpressSourceData;
import com.rtx.edi.platform.source.service.PlExpressSourceDataService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@SuppressWarnings("all")
@Api(tags = {"源数据"})
@RestController
@RequestMapping("/v1/PlExpressSourceData")
public class PlExpressSourceDataController {
	
	Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	PlExpressSourceDataService configService;
	
	@Autowired
	ApplicationContext context;
	
	
	@ApiOperation(value = "获取已经配置的数据源", notes = "获取已经配置的数据源")
	@PostMapping("selectSTDDatasourckey")
	public EdiResponse querySTDJob(@RequestBody String request) {
		String[] names = context.getBeanNamesForType(DataSource.class);
		
		List<Map<String,String>>jobs =new ArrayList<>();
		
		Map<String,String> nullData =new HashMap<String, String>();
		nullData.put("label", "");
		nullData.put("value", "");
		jobs.add(nullData);
		
		for(String name:names) {
			String label ="";
			if(name.startsWith("ris_edi")) {
				label ="接口平台数据源";
			}else if(name.startsWith("wmwhse")) {
				label ="仓库"+name.replace("wmwhse", "")+"数据源";
			}else if("enterprise".equals(name)) {
				label ="企业级数据源";
			}else {
				continue;
			}
			
	
			Map<String,String> data =new HashMap<String, String>();
			data.put("label", label);
			data.put("value", name);
			jobs.add(data);
		}

		
		return EdiResponse.success().data("item", jobs);
	}
	
	@ApiOperation(value = "获取已经配置的数据源sql字段", notes = "获取已经配置的数据源sql字段")
	@PostMapping("selectMainSqlField")
	public EdiResponse queryMainSqlField(@RequestBody String dto) {
		List<Map<String,String>> fields =new ArrayList<>();

		Map<String,String> nullData =new HashMap<String, String>();
		nullData.put("label", "");
		nullData.put("value", "");
		fields.add(nullData);

		PlExpressSourceData data = configService.getById(JSON.parseObject(dto).getLong("id"));
		String datasourckey = data.getDatasourcekey();
		DataSource dataSource = (DataSource) context.getBean(datasourckey);
		Set<String> colums = new HashSet<>();
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
			PreparedStatement statement = connection.prepareStatement(data.getConfigsql());
			ResultSet resultSet = statement.executeQuery();
			ResultSetMetaData rsmd = resultSet.getMetaData();
			for (int i = 0; i < rsmd.getColumnCount(); i++) {
				if (!colums.contains(rsmd.getColumnLabel(i + 1))) {
					colums.add(rsmd.getColumnLabel(i + 1));
				}
			}
		} catch (Exception e) {
			log.error("",e);
		}finally {
			try {
				connection.close();
			} catch (SQLException e) {
				log.error("",e);
			}
		}

		colums.forEach(temp->{
			Map<String,String> eachData =new HashMap<String, String>();
			eachData.put("label", temp);
			eachData.put("value", temp);
			fields.add(eachData);
		});
		return EdiResponse.success().data("item", fields);
	}
	
    /**
     * 获取源数据列表
     * @return
     */
    @ApiOperation(value = "源数据列表", notes = "分页获取源数据列表")
    @PostMapping("selectExpressSourceDataList")
    public EdiResponse selectExpressApiConfigPageList(@RequestBody PlExpressSourceData dto){
        Page<PlExpressSourceData> pageParam = new Page<>(dto.getPageNum(), dto.getPageSize());
        configService.selectList(pageParam,dto);
        return EdiResponse.success().data("page",pageParam);
    }

    /**
     * 获取源数据
     * @return
     */
    @ApiOperation(value = "获取源数据", notes = "根据ID获取源数据")
    @PostMapping("selectExpressSourceDataById")
    public EdiResponse selectExpressApiConfigById(@RequestBody PlExpressSourceData dto){
        return EdiResponse.success().data("item",configService.getById(dto.getId()));
    }

    /**
     * 新增源数据
     * @return
     */
    @ApiOperation(value = "新增源数据", notes = "新增源数据")
    @PostMapping("addExpressSourceData")
    public EdiResponse addExpressApiConfig(@RequestBody PlExpressSourceData dto){
        //验证非空字段
        configService.addData("ris_edi", dto);
        return  EdiResponse.success() ;
    }

    /**
     * 修改源数据
     * @return
     */
    @ApiOperation(value = "修改源数据", notes = "根据ID修改源数据")
    @PostMapping("editExpressSourceData")
    public EdiResponse editExpressApiConfig(@RequestBody PlExpressSourceData dto){
    	configService.updateById(dto);
        return  EdiResponse.success();
    }

    /**
     * 删除源数据
     * @return
     */
    @ApiOperation(value = "删除源数据", notes = "根据ID删除源数据")
    @PostMapping("deleteExpressSourceData")
    public EdiResponse deletePlApplicationFieldById(@RequestBody PlExpressSourceData dto){
        FieldValidateUtils.fieldNotNull(dto,FieldValidateType.DELETE);
        return  configService.removeById(dto.getId()) ? EdiResponse.success() : EdiResponse.failed();
    }

    /**
     * 批量删除源数据
     * @return
     */
    @ApiOperation(value = "批量删除源数据", notes = "批量删除源数据")
    @PostMapping("deleteExpressSourceDataIds")
    public EdiResponse deletePlApplicationFieldByIds(@RequestBody List<PlExpressSourceData> list){
        List<Long> ids = list.stream().map(p -> p.getId()).distinct().collect(Collectors.toList());
        return  configService.removeBatchByIds(ids) ? EdiResponse.success() : EdiResponse.failed();
    }
}
